package sample.util;

import sample.context.Context;
import sample.context.ContextValues;
import sample.context.StageManager;
import sample.controller.MainController;
import sample.pojo.User;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author ：five03
 * @description：TODO
 * @date ：2020/8/13 9:59 上午
 */

public class ChatReceive extends Thread{
    DatagramSocket socket = null;

    public ChatReceive() {
        try {
            this.socket = new DatagramSocket(ContextValues.port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    public void run(){
        while (true) {
            try {
                // 接受
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container, 0, container.length);
                socket.receive(packet);
                byte[] data = packet.getData();
                String receive = new String(data, "UTF-8").trim();

                // 中断
                if(receive.equals("0")){
                    break;
                }

                // 处理字符串
                decodeText(receive,packet.getAddress().toString());

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }

    // 消息处理
    private void decodeText(String text,String fromIP){
        System.out.println("===>收到消息:");
        System.out.println(fromIP + "===>" + text);
        // 好友申请  999@用户名@用户IP
        if(text.startsWith(ContextValues.addUserCode)){
            String s[] = text.split("@");

            // 好友列表中已存在
            if (Context.USERS.containsKey(s[2].trim())) return;

            // 添加好友
            User user = new User(s[1],s[2].trim());
            Context.addUser(user);
            // 刷新好友列表
            MainController controller = (MainController) StageManager.CONTROLLER.get("MainController");
            controller.refreshUserList();

            System.out.println("===>好友申请" + s[1] + " " + s[2]);

            String ss = ContextValues.addUserCode + "@" + ContextValues.adminUserName + "@" + ContextValues.hostIp;
            ChatSent.sendUserReq(ss,s[2],ContextValues.port);

        } else {
            // 好友消息
            int index = text.indexOf("@");
            String IP = text.substring(0, index);
            String msg = text.substring(index + 1);
            if(IP.isEmpty() || msg.isEmpty()) return;

            // 若在好友列表添加至消息记录 若不在添加至陌生人记录
            User user = Context.USERS.get(IP);
            if (user == null)
                user = Context.USERS.get(ContextValues.strangerIP);

            String s = Context.getDate() + "\t"
                    + Context.getName(IP)
                    + fromIP
                    + ":\n" + msg.trim() + "\n";

            user.saveChattingRecord(s);

            // 刷新消息列表
            if (user == Context.NOWCHATING){
                MainController controller = (MainController) StageManager.CONTROLLER.get("MainController");
                controller.refreshOutputTextList();
            }
        }
    }
}
